<template>
  <!-- 会员等级-选择优惠券 -->
  <el-dialog
    v-model="visible"
    :title="$t('user.selectCoupons')"
    top="5vh"
    :before-close="close"
    :close-on-click-modal="false"
    :append-to-body="visible"
    destroy-on-close
  >
    <div class="prods-select-body">
      <el-table
        ref="couponTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        header-cell-class-name="table-header"
        row-class-name="table-row-low"
        :row-key="getRowKeys"
        style="width: 100%;"
        height="600"
        @selection-change="selectChangeHandle"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
        >
          <template #default="scope">
            <div>
              <!-- native modifier has been removed, please confirm whether the function has been affected  -->
              <el-radio
                v-model="singleSelectCouponId"
                :label="scope.row.couponId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          :reserve-selection="true"
          width="50"
        />
        <el-table-column
          prop="couponName"
          :label="$t('marketing.couponName')"
        >
          <template #default="scope">
            <div class="table-cell-text">
              {{ scope.row.couponName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="couponType"
          :label="$t('coupon.couponType')"
        />
        <el-table-column
          prop="limitNum"
          :label="$t('user.couponUpperLimit')"
        />
      </el-table>
    </div>
    <el-pagination
      class="pagination"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="close"
        >
          {{ $t("user.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="submitProds()"
        >
          {{ $t("user.confirm") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  // 获取方式 null:默认（客户领取+平台发放） 0=客户领取 1=平台发放
  getWay: {
    default: null,
    type: Number
  },
  dataUrl: {
    default: '/platform/coupon/list',
    type: String
  }
})
const emit = defineEmits(['refreshSelectCouponList'])

const dataForm = reactive({
  product: ''
})
const singleSelectCouponId = ref(0)

onActivated(() => {
  getDataList()
})

const couponTableRef = ref(null)
onBeforeUnmount(() => {
  couponTableRef.value?.clearSelection()
})

const visible = ref(false)
const dataList = ref([])
const close = () => {
  dataList.value.forEach(row => {
    couponTableRef.value?.toggleRowSelection(row, false)
  })
  visible.value = false
}

let selectCoupons = []
const dataListLoading = ref(false)
let dataListSelections = []
// 获取数据列表
const init = (selectCouponsPar = []) => {
  selectCoupons = selectCouponsPar
  visible.value = true
  dataListLoading.value = true
  if (selectCoupons) {
    selectCoupons.forEach(row => {
      dataListSelections.push(row)
    })
  }
  getDataList()
}

const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value
        },
        {
          prodName: dataForm.prodName,
          getWay: props.getWay
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    dataList.value.forEach(item => {
      // 平台投放 / 用户领取
      item.couponType = item.couponType === 1 ? $t('coupon.voucher') : (item.couponType === 2 ? $t('coupon.discountVoucher') : (item.couponType === 3 ? $t('coupon.coinCertificate') : ''))
    })
    totalPage.value = data.total
    dataListLoading.value = false
    if (selectCoupons.length) {
      nextTick(() => {
        selectCoupons.forEach(row => {
          const index = dataList.value.findIndex((couponItem) => couponItem.couponId === row.couponId)
          if (index >= 0) {
            couponTableRef.value?.toggleRowSelection(dataList.value[index], true)
          }
        })
      })
    }
  })
}

// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}

// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}

// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections = [row]
}

// 多选点击事件
const selectChangeHandle = (selection) => {
  dataListSelections = selection
}

// 记录选中状态
const getRowKeys = (row) => {
  return row.couponId
}

// 确定事件
const submitProds = () => {
  // 商品单选的情况
  if (props.isSingle) {
    dataListSelections.length && emit('refreshSelectCouponList', dataListSelections[0])
    dataListSelections = []
    visible.value = false
    return
  }
  // 多选
  const coupons = []
  if (dataListSelections.length < 1) {
    emit('refreshSelectCouponList', [])
  } else {
    dataListSelections.forEach(item => {
      const couponIndex = coupons.findIndex((coupon) => coupon.couponId === item.couponId)
      if (couponIndex === -1) {
        coupons.push({ couponId: item.couponId, couponName: item.couponName, subTitle: item.subTitle, limitNum: item.limitNum })
      }
    })
    emit('refreshSelectCouponList', coupons)
  }
  dataListSelections = []
  visible.value = false
}

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
.prods-select-body {
  height: 601px;
  overflow: auto;
  border-top: 1px solid #eeeeee;
  border-right: 1px solid #eeeeee;
}
.table-cell-text {
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  word-break: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  overflow: hidden;
  -webkit-box-orient: vertical;
  line-height: 20px;
}
.pagination {
  margin-top: 20px;
}
</style>
